package com.example.cici.cclight;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.example.cici.cclight.util.PersonSer;
import com.example.cici.cclight.util.Personpar;
import com.example.cici.cclight.util.SocketUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class List_Bluetooth extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener{
    private static final int REQUEST_PERMISSION_ACCESS_LOCATION = 1;
    private ListView mList;//显示蓝牙
    private ArrayList<BluetoothDevice> strArr;
    private BluetoothAdapter blueToothAdapter;
    private ListViewAdapter adapter;
    private Button mSearch;
    private UUID   uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static final int startService = 0;
    private static final int getMessageOk = 1;
    private static final int sendOver = 2;
    private BluetoothSocket socket;
    private Button Tohome;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case sendOver:
                    Toast.makeText(List_Bluetooth.this, "发送成功", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_bluetooth);
        //获取本设备的蓝牙设配器实例，判断本设备是否有蓝牙功能，有则返回实例，没则返回null
        blueToothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (blueToothAdapter != null) {
            mSearch = (Button) findViewById(R.id.btn_search);//搜索蓝牙按钮
            mSearch.setOnClickListener(this);
            mList = (ListView) findViewById(R.id.list);//存搜索出来的蓝牙设备
            Tohome = (Button) findViewById(R.id.btn_tree);
            Tohome.setOnClickListener(this);
            strArr = new ArrayList<>();//存以绑定的蓝牙设备
            adapter = new ListViewAdapter();
            mList.setAdapter(adapter);
            mList.setOnItemClickListener(this);
            //注册广播，接收其他蓝牙设备
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
            intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
            registerReceiver(new BluetoothReceiver(), intentFilter);
        }
    }

    //判断是否有蓝牙开启权限
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkAccessFinePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (checkAccessFinePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        REQUEST_PERMISSION_ACCESS_LOCATION);
                Log.e(getPackageName(), "没有权限，请求权限");
                return;
            }
            Log.e(getPackageName(), "已有定位权限");
            search();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.e(getPackageName(), "开启权限permission granted!");
                    //做下面该做的事
                    search();
                } else {
                    Log.e(getPackageName(), "没有定位权限，请先开启!");
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //开始搜素蓝牙
    public void search() {
        strArr.clear();
        if (blueToothAdapter.isDiscovering())
            blueToothAdapter.cancelDiscovery();
        blueToothAdapter.startDiscovery();
        Log.e(getPackageName(), "开始搜索");
    }

    //获取以绑定设备
    public void getBindDevice() {
        Set<BluetoothDevice> bondedDevices = blueToothAdapter.getBondedDevices();
        strArr.clear();
        strArr.addAll(bondedDevices);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_search:
                requestPermission();
                break;
            case R.id.btn_tree:
                Intent intent = new Intent();
//                Bundle bundle = new Bundle();
//                PersonSer personSer = new PersonSer();
//                personSer.setSocket("socket");
                intent.setClass(List_Bluetooth.this,thrid_activity.class);
                startActivity(intent);
        }
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {

        //点击Item的时候，如果还在搜索，停止搜索
        if (blueToothAdapter.isDiscovering())
            blueToothAdapter.cancelDiscovery();
        if (strArr.get(i).getBondState() == BluetoothDevice.BOND_NONE) {
            bond(i);
            adapter.notifyDataSetChanged();
        } else if (strArr.get(i).getBondState() == BluetoothDevice.BOND_BONDED) {
           sendMessage(i);
            }
        }

    //蓝牙通信，接收信息
    private boolean getMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream is = null;
                try {
                    BluetoothServerSocket serverSocket = blueToothAdapter.listenUsingRfcommWithServiceRecord("serverSocket", uuid);
                    mHandler.sendEmptyMessage(startService);
                    BluetoothSocket accept = serverSocket.accept();
                    is = accept.getInputStream();
                    byte[] bytes = new byte[1024];
                    int length = is.read(bytes);
                    Message msg = new Message();
                    msg.what = getMessageOk;
                    msg.obj = new String(bytes, 0, length);
                    mHandler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return true;
    }


    //蓝牙通信函数，发送信息
    private boolean sendMessage(final int i) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OutputStream os = null;
                try {
                    socket = strArr.get(i).createRfcommSocketToServiceRecord(uuid);
                    socket.connect();
                    SocketUtil.getInstance().setBluetoothSocket(socket);
                    os = socket.getOutputStream();
                    os.write("+C,12:255,0,0;".getBytes());
                    os.flush();
                    mHandler.sendEmptyMessage(sendOver);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return true;
    }


    //蓝牙配对函数
    private boolean bond(int i) {
        try {
            Method method = BluetoothDevice.class.getMethod(  "createBond");
            Log.e(getPackageName(), "开始配对");
            method.invoke(strArr.get(i));
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    class ListViewAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return strArr.size();
        }
        @Override
        public Object getItem(int i) {
            return strArr.get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = LayoutInflater.from(List_Bluetooth.this).inflate(android.R.layout.simple_list_item_1, viewGroup, false);
            BluetoothDevice device = strArr.get(i);
            ((TextView) view).setText(device.getName() + "-----" + (device.getBondState() == BluetoothDevice.BOND_BONDED ? "已绑定" : "未绑定"));
            return view;
        }
    }

    class BluetoothReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
                Log.e(getPackageName(), "找到新设备了");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                boolean addFlag = true;
                for (BluetoothDevice bluetoothDevice : strArr) {
                    if (device.getAddress().equals(bluetoothDevice.getAddress())) {
                        addFlag = false;
                    }
                }
                if (addFlag) {
                    strArr.add(device);
                    adapter.notifyDataSetChanged();
                }
            } else if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_NONE:
                        Log.e(getPackageName(), "取消配对");
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        Log.e(getPackageName(), "配对中");
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        Log.e(getPackageName(), "配对成功");
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        }
    }

}
